import React, {useState, useEffect, useRef} from 'react'
import {Avatar, Modal, Image, DatePicker, message, Space, Upload} from 'antd';
import {ModalForm, ProFormDateRangePicker, ProFormSelect, ProTable} from '@ant-design/pro-components';
import TheButton from "@/components/TheButton/index.jsx";
import moment from 'moment';
import {
    apiPlatformActivitySheetPage,
    apiGetActivityConfig,
    apiPlatformActivitySheetExcelExport,
    apiPlatformActivitySheetUpdateActivityStatus,
    apiPlatformActivitySheetDel
} from "../../../api/activityManager/index.js";
import {useNavigate} from "react-router-dom";
import {apiGetCouponTimerCenterDel} from "@/api/couponManagement/timeTask.jsx";
import {useWindowSize} from "@/utils/useWindowSize.js";

const {confirm} = Modal;
const {RangePicker} = DatePicker;

export default () => {
    const {width, height} = useWindowSize();
    const [tbScrollH, setTbScrollH] = useState('40vh');
    const [loadings, setLoadings] = useState([]);
    const [butIndex, setButIndex] = useState();
    const navigate = useNavigate()
    const [modalVisit, setModalVisit] = useState(false);
    const [memberId, setMemberId] = useState();
    const actionRef = useRef();
    const [onOffActivityLoading, setOnOffActivityLoading] = useState(false);
    const columns = [
        {
            title: "活动名称",
            dataIndex: "activityName",
            key: "activityName",
        },
        // {
        //   title: "门店名称",
        //   dataIndex: "storeName",
        //   key: "storeName",
        //   hideInSearch: true,
        // },
        {
            title: "活动类型",
            dataIndex: "activityType",
            key: "activityType",
            valueType: 'select',
            fieldProps: {
                fieldNames: {
                    label: "platformSetShowValue",
                    value: "platformSetUseValue"
                }
            },
            request: async () => {
                let res = await apiGetActivityConfig({platformSetKey: 'ACTIVITY_TYPE'});
                if (res.code === 0) {
                    return res.data
                } else return []
            }
        },
        {
            title: "活动链接/活动ID",
            dataIndex: "activityId",
            key: "activityId",
            hideInSearch: true,
        },
        {
            title: "活动状态",
            dataIndex: "activityStatus",
            key: "activityStatus",
            valueType: 'select',
            fieldProps: {
                options: [
                    {value: 0, label: '正常'},
                    {value: 1, label: '关闭'},
                ]
            },
            width: 100
        },
        {
            title: "定时任务",
            dataIndex: "activityTime",
            key: "activityTime",
            hideInSearch: true,
            render: (text, render) => {
                let txt = ''
                switch (render.timeType) {
                    case '0':
                        txt = '/'
                        break;
                    case '1':
                        txt = render.startTime + '至' + render.endTime
                        break;
                    default:
                        txt = '/'
                        break;
                }
                return txt;
            },
        },
        {
            title: "活动方式",
            dataIndex: "activityWay",
            key: "activityWay",
            valueType: 'select',
            hideInSearch: true,
            fieldProps: {
                fieldNames: {
                    label: "platformSetShowValue",
                    value: "platformSetUseValue"
                }
            },
            request: async () => {
                let res = await apiGetActivityConfig({platformSetKey: 'ACTIVITY_WAY'});
                if (res.code === 0) {
                    return res.data
                } else return []
            },
            width: 150
        },
        {
            title: "操作",
            valueType: 'option',
            fixed: "right",
            width: 500,
            render: (text, render, index) => {
                // 多按钮防连点loading
                let flag = []
                if (loadings.length) {
                    if (loadings[index]) {
                        flag[butIndex] = loadings[index][butIndex];
                    }
                }
                return (
                    <Space style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'center'}}>
                        <TheButton haspermi={['activityManager:list:edit']} type={'link'} onClick={() => onEdit(render.activityId)}>编辑</TheButton>
                        <TheButton haspermi={['activityManager:list:participation']} type={'link'} onClick={() => onJoinUser(render.activityId)}>参与用户</TheButton>
                        {
                            ['NEW_COME', 'SHOP_GOODS'].includes(render.activityType) ?
                                <TheButton haspermi={['activityManager:list:export']} type={'link'} onClick={() => exportActivity(render, index, 0)}
                                           loading={flag[0]}>导出活动</TheButton> : null
                        }
                        {
                            render.activityStatus === 0 &&
                            <TheButton haspermi={['activityManager:list:endActivity']} type={'link'} onClick={() => onUpdateActivity(render.activityId, '1', index, 1)}
                                       loading={flag[1]}>结束活动</TheButton>
                        }
                        {
                            render.activityStatus === 1 &&
                            <TheButton haspermi={['activityManager:list:startActivity']} type={'link'} onClick={() => onUpdateActivity(render.activityId, '0', index, 1)}
                                       loading={flag[1]}>开启活动</TheButton>
                        }
                        <TheButton haspermi={['activityManager:list:del']} type={'link'} onClick={() => onDel(render.activityId, index, 2)}
                                   loading={flag[2]}>删除</TheButton>
                    </Space>
                );
            },
        },
    ]
    useEffect(() => {
        if (height >= 1080){
            setTbScrollH('58vh')
        }else if(height < 1080 && height >= 960){
            setTbScrollH('43vh')
        }
    }, [])

    const openDialog = (id) => {
        setMemberId(id)
        setModalVisit(true)
    }
    const onAdd = () => {
        navigate('/activityManager/list/event', {
            state: {
                mode: "add"
            }
        })
    }
    const onEdit = (activityId) => {
        navigate('/activityManager/list/event', {
            state: {
                mode: "edit",
                activityId
            }
        })
    }
    const onJoinUser = (activityId) => {
        navigate('/activityManager/list/user', {
            state: {
                mode: "user",
                activityId
            }
        })
    }
    // 导出活动
    const exportActivity = async (row, RowIndex, ButIndex) => {
        setButIndex(ButIndex);
        setLoadings((prevLoadings) => {
            const newLoadings = [...prevLoadings];
            newLoadings[RowIndex] = {
                [ButIndex]: true
            };
            return newLoadings;
        });
        const res = await apiPlatformActivitySheetExcelExport({activityId: row.activityId})
        let a = document.createElement("a");
        let url = window.URL.createObjectURL(new Blob([res]));
        a.href = url;
        a.download = row.activityName + '(' + row.activityId + ')' + ".xlsx";
        a.style.display = "none";
        document.body.appendChild(a);
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
        setTimeout(() => {
            setLoadings((prevLoadings) => {
                const newLoadings = [...prevLoadings];
                newLoadings[RowIndex] = {
                    [ButIndex]: false
                };
                return newLoadings;
            });
        }, 1000)
    }

    // 开启关闭活动
    const onUpdateActivity = async (activityId, type, RowIndex, ButIndex) => {
        setButIndex(ButIndex);
        setLoadings((prevLoadings) => {
            const newLoadings = [...prevLoadings];
            newLoadings[RowIndex] = {
                [ButIndex]: true
            };
            return newLoadings;
        });
        Modal.confirm({
            title: '提示',
            content: '确定变更活动状态？',
            onOk: async () => {
                await apiPlatformActivitySheetUpdateActivityStatus({activityId, type}).then((res) => {
                    if (res.code === 0) {
                        message.success('操作成功')
                        actionRef.current.reload()
                    }
                    // setOnOffActivityLoading(false)
                    // return false
                    // } else {
                    //   // setOnOffActivityLoading(false)
                    //   loadingSet(index, false)
                    //   // message.success(res.codeMessage)
                    //   // return false
                    // }
                })
                setLoadings((prevLoadings) => {
                    const newLoadings = [...prevLoadings];
                    newLoadings[RowIndex] = {
                        [ButIndex]: false
                    };
                    return newLoadings;
                });
            },
            onCancel: () => {
                setLoadings((prevLoadings) => {
                    const newLoadings = [...prevLoadings];
                    newLoadings[RowIndex] = {
                        [ButIndex]: false
                    };
                    return newLoadings;
                });
                // setOnOffActivityLoading(false)
            }
        })
    }
    //删除活动
    const onDel = async (activityId, RowIndex, ButIndex) => {
        setButIndex(ButIndex);
        setLoadings((prevLoadings) => {
            const newLoadings = [...prevLoadings];
            newLoadings[RowIndex] = {
                [ButIndex]: true
            };
            return newLoadings;
        });
        confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                await apiPlatformActivitySheetDel({activityId}).then((res) => {
                    if (res.code === 0) {
                        message.success('操作成功')
                        actionRef.current.reloadAndRest()
                        return false
                    } else {
                        message.success(res.codeMessage)
                        return false
                    }
                })
                setButIndex(ButIndex);
                setLoadings((prevLoadings) => {
                    const newLoadings = [...prevLoadings];
                    newLoadings[RowIndex] = {
                        [ButIndex]: false
                    };
                    return newLoadings;
                });
            },
            onCancel: () => {
                setLoadings((prevLoadings) => {
                    const newLoadings = [...prevLoadings];
                    newLoadings[RowIndex] = {
                        [ButIndex]: false
                    };
                    return newLoadings;
                });
            }
        })
    }
    return <div>
        <ProTable
            actionRef={actionRef}
            scroll={{x: 960, y: tbScrollH}}
            rowKey={(record) => record.activityId}
            bordered={true}
            options={false}
            columns={columns}
            headerTitle={
                <Space>
                    <TheButton
                        haspermi={['activityManager:list:add']}
                        key="new"
                        onClick={() => {
                            onAdd()
                        }}
                    >
                        创建活动
                    </TheButton>
                    {/*<TheButton*/}
                    {/*    key="img"*/}
                    {/*    onClick={() => {*/}

                    {/*    }}*/}
                    {/*>*/}
                    {/*    配置价格图片*/}
                    {/*</TheButton>*/}
                </Space>
            }
            pagination={{
                defaultPageSize: 10,
                position: ['bottomCenter'],
                showSizeChanger: false
            }}
            request={async (params, sort, filter) => {
                // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
                // 如果需要转化参数可以在这里进行修改
                const res = await apiPlatformActivitySheetPage({
                    pageNo: params.current,
                    pageSize: params.pageSize,
                    ...params
                });
                return {
                    data: res.data,
                    // success 请返回 true，
                    // 不然 table 会停止解析数据，即使有数据
                    success: res.code === 0,
                    // 不传会使用 data 的长度，如果是分页一定要传
                    total: res.totalCount,
                };
            }}
            search={{
                optionRender: (searchConfig, formProps, dom) => {
                    return dom.reverse()
                },
                collapsed: false,
                collapseRender: false
            }}
        />
        <ModalForm
            title="发放优惠券"
            layout={'horizontal'}
            labelCol={{span: 5}}
            wrapperCol={{span: 19}}
            width={500}
            open={modalVisit}
            modalProps={{
                destroyOnClose: true,
                onCancel: () => setModalVisit(false),
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
                // let res = await apiGetByCouponCentre({
                //     ...values,
                //     memberId: memberId,
                //     sourceId: 2
                // })
                // if (res.code === 0 && res.data) {
                //     if (res.data.success){
                //         message.info('发放成功')
                //         // 刷新
                //         actionRef.current.reload();
                //         setModalVisit(false)
                //     }else {
                //         message.info(res.data.msg)
                //     }
                // }
                return false;
            }}
        >

        </ModalForm>
    </div>
}
